package com.powernode.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.powernode.constant.WxConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.core.parameters.P;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.time.Duration;

/**
 * 内容:
 * 作者: cy
 */
@EnableConfigurationProperties(WxMsgProperties.class)
@Configuration
public class WxMsgAutoConfiguration {

    @Autowired
    private WxMsgProperties wxMsgProperties;

    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 我们希望这个方法 要先执行
     */
    @PostConstruct
    public void init() {
        refreshWxToken();
    }


    @Scheduled(fixedRate = 7000 * 1000)
    public void refreshWxToken() {
        String realTokenUrl = String.format(wxMsgProperties.getWxTokenUrl(), wxMsgProperties.getAppId(), wxMsgProperties.getAppSecret());
        String wxTokenStr = restTemplate.getForObject(realTokenUrl, String.class);
        JSONObject jsonObject = JSON.parseObject(wxTokenStr);
        String accessToken = jsonObject.getString("access_token");
        if (StringUtils.hasText(accessToken)) {
            redisTemplate.opsForValue().set(WxConstant.WX_TOKEN_KEY, accessToken, Duration.ofSeconds(7200));
            return;
        }
        System.out.println("获取token失效，人工处理" + jsonObject.toJSONString());
    }


}
